<!--
* @description 巡检点位
* @author xyjia
* @date 2022/01/11 10:31:54
!-->
<template>
  <div class="inspect-main pointedit">
    <van-nav-bar title="巡检点位" fixed left-arrow @click-left="onClickLeft" />
    <div class="inspect-all">
      <div class="inspect-all-top">基本信息录入</div>
    </div>
    <van-form @submit="onSubmit">
        <van-field
          v-model="EditParam.name"
          class="fieldwithmagrin"
          required
          name="name"
          label="点位名称"
          placeholder="请输入点位名称"
          autosize
          rows="1"
          type="textarea"
          :rules="[{ required: true, message: '请输入点位名称' }]"
        />
      <van-cell-group>
         <van-field
          v-model="EditParam.pointCode"
          class="fieldwithmagrin"
          label-class="otherleftfieldcss"
          name="pointCode"
          label="二维码编码"
          autosize
          rows="1"
          type="textarea"
          readonly 
          disabled
        />
      </van-cell-group>
      <van-cell-group>
         <van-field
            v-model="selectedPoint"
            required
            readonly
            clickable
            class="fieldwithmagrin"
            name="pointTypeId"
            label="点位类别" 
            placeholder="请选择点位类别"
            :disabled="EditParam.id !==''?true:false"
            @click="EditParam.id==''?showpointPicker = true:$toast('点位不可编辑')"
            :rules="[{ required: true, message: '请选择点位类别', trigger: 'blur' }]"
          />
         <van-action-sheet
            ref="action"
            title="请选择点位类别"
            v-model="showpointPicker"
            :actions="options_point"
            @select="onSelect"
          />
      </van-cell-group>
      <van-cell-group  v-if="userInfo.isMuilUnitUser">
         <van-field
          v-model="orgIdValue"
          required
          readonly
          clickable
          class="fieldwithmagrin"
          name="orgId"
          label="所属单位" 
          placeholder="请选择单位"
          :disabled="EditParam.id !==''?true:false"
          @click="EditParam.id==''?showorgIdPicker = true:$toast('单位不可编辑')"
          :rules="[{ required: true, message: '请选择单位', trigger: 'blur' }]"
        />
        <unit-picker
            ref="popUnit"
            :showIcon="false"
            :otheractive="showorgIdPicker"
            :currentOrgprops="currentOrgprops"
            @change="onorgIdChange"
            @onClose="onorgIdClose"
            style="height:0px"
        ></unit-picker>
      </van-cell-group>
      <van-cell-group>
         <van-field
          v-model="fbsIdValue"
          required
          readonly
          clickable
          class="fieldwithmagrin"
          name="fbsId"
          label="所属建筑物" 
          placeholder="请选择建筑物"
          @click="EditParam.orgId!==''?showfbsIdPicker = true:$toast('请先选择单位')"
          :rules="[{ required: true, message: '请选择建筑物', trigger: 'blur' }]"
        />
        <van-popup v-model="showfbsIdPicker" round position="bottom">
          <van-cascader
            title="请选择所属建筑物"
            :options="options_fbsId"
            active-color="#2471CA"
            :field-names="fieldNames"
            @close="showfbsIdPicker = false"
            @finish="onFinish"
          />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="EditParam.address"
          class="fieldwithmagrin"
          name="address"
          label="具体地址"
          placeholder="请输入具体地址"
          autosize
          rows="1"
          type="textarea"
        />
      </van-cell-group>
      <div class="uploadPictitle_big">
        <div class="uploadPictitle_left">安装位置照片</div>
        <!-- （不低于1张，不高于9张） -->
        <div class="uploadPictitle_right"></div>
      </div>
      <van-field name="picUrl" label="">
        <template #input class="uploadwithcss">
          <van-uploader 
            v-model="picUrlData" 
            :max-count="1"
            :after-read="afterRead"
            :before-delete="beforedelete"
            accept="image/png, image/jpg, image/jpeg"
          />
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button block color="#2471CA" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { qiniuUpload } from '@/utils/util'
import UnitPicker from '@/components/UnitPicker'
import { mapState } from 'vuex'
import {getLists, addExaminePoint} from '@/api/examine'
import { getOrgFbsTree } from '@/api/common'
export default {
  data() {
    return {
      picUrlData: [],
      alldetailData : {},
      EditParam: {
        id: '',
        name: '',
        pointCode: '',
        pointTypeId:'', // 点位类别ID
        orgId: '', // 所属单位ID
        fbsId: '', // 所属建筑物 ID
        address: '',
        picUrl: []
      },
      currentOrgprops: {},
      showpointPicker: false,
      showorgIdPicker: false,
      showfbsIdPicker: false,
      fbsIdValue: '', //所属建筑物 名称
      orgIdValue: '', //所属单位 名称
      selectedPoint: '', // 点位类别 名称
      options_point: [],
      options_fbsId: [],
      fieldNames: {
        text: 'text',
        value: 'id',
        children: 'nodes',
      },
    }
  },
  components: {UnitPicker},

  watch: {},

  computed: {
    ...mapState(['qiniuPath','userInfo']),
  },

  created() {
    if (this.$route.query.detailData) {
      this.alldetailData  = JSON.parse(this.$route.query.detailData) || {}
      this.EditParam.name = this.alldetailData.name
      this.EditParam.id = this.alldetailData.id
      this.EditParam.pointCode = this.alldetailData.pointCode
      this.EditParam.pointTypeId = this.alldetailData.pointTypeId
      this.selectedPoint = this.alldetailData.typeName
      this.EditParam.orgId = this.alldetailData.orgId
      this.EditParam.fbsId = this.alldetailData.fbsId
      this.orgIdValue = this.alldetailData.orgName
      this.fbsIdValue = this.alldetailData.buildLevelName
      this.EditParam.address = this.alldetailData.address
      this.picUrlData = this.alldetailData.picUrl.length==0?[]:[{url:this.alldetailData.picUrl}]
      this.EditParam.picUrl = this.alldetailData.picUrl.length==0?[]:[this.alldetailData.picUrl]
    } else {
      this.EditParam.pointCode = this.$route.query.pointCode
      this.EditParam.orgId= this.userInfo.isMuilUnitUser==1?'':this.userInfo.organizationIds,
      this.EditParam.picUrl = []
    }
    this.currentOrgprops = {} //重置单位
     this.getListsdata()
     this.getOrgFbsTree()
     
  },
  mounted() {},
  methods: {
    // 上传图片
    afterRead({ file }) {
      if (file.type.substr(0, 5) === 'video') {
        Toast(`巡检暂不支持上传视频`)
      } else {
        this.requestUpload(file)
      }
    },
    requestUpload(file) {
      qiniuUpload(file, {
        next: (res) => {
          // ...
        },
        error: (err) => {
          // ...
        },
        complete: (res) => { 
          this.EditParam.picUrl.push(
            uploadOnNginx ? res.data : this.qiniuPath + res.key
          )
          
          this.picUrlData = []
          this.picUrlData = this.EditParam.picUrl.map(n => {
            return {url: n}
          })
          console.log('this.picUrlData',this.picUrlData)
        },
      })
    },
    // 删除照片
    beforedelete(file,detail ) {
       this.EditParam.picUrl.splice(detail.index, 1)
       this.picUrlData.splice(detail.index, 1)
    },
    // 建筑物数据
    getOrgFbsTree() {
      getOrgFbsTree({
        orgIds: this.EditParam.orgId,//this.userInfo.isMuilUnitUser==1?this.userInfo.organizationIds:this.userInfo.org.id,
        buildId: 0,
      }).then((res) => {
        let list = res.data
        this.options_fbsId = list 
      })
    },
    // 所属建筑物筛选确认 结果
    onFinish({ selectedOptions }) {
      this.showfbsIdPicker = false;
      this.fbsIdValue = selectedOptions.map((option) => option.text).join('>')
      this.EditParam.fbsId = selectedOptions[selectedOptions.length-1].id
    },
    // 点位数据
    getListsdata() {
      getLists({queryType: 0}).then((res) => {
         this.options_point = res.data?res.data.map(n => {
           n.name = n.pointTypeName
            return n
         }): []
      })
    },
    onSubmit(values) {
      values.pointTypeId = this.EditParam.pointTypeId
      values.fbsId = this.EditParam.fbsId
      values.orgId = this.EditParam.orgId
      values.picUrl = this.EditParam.picUrl.toString()
      values.id = this.EditParam.id
      values.codeType = 2
      values.createAccount = this.userInfo.accountName
      // console.log('submit', values);

      addExaminePoint(values).then((res) => {
          this.$toast(res.info)
          if (res.status == 200) {
            if (values.id == '') {
              this.$router.go(-1)
            } else {
              this.$router.go(-2)
            }
            
          }
      })
    },
    onClickLeft() {
        this.$router.go(-1)
    },
    // 单位选择器
    onorgIdChange(obj) {
        // 选单位重置建筑物
        this.fbsIdValue = ''
        this.EditParam.fbsId = ''

        // 选单位结果赋值
        this.orgIdValue = obj.shortName
        this.EditParam.orgId = obj.organizationId
        if (obj.organizationId) {
            this.getOrgFbsTree()
        }
    },
    // false重置单位pick弹框状态
    onorgIdClose() {
      this.showorgIdPicker = false
    },
    // 点位类别 选择器
    onSelect(action) {
      this.showpointPicker = false
      this.selectedPoint = action.pointTypeName
      this.EditParam.pointTypeId = action.id
      this.selectedPoint_select(action)
    },
    selectedPoint_select(val) {
      this.options_point.forEach((n) => {
        this.$set(
          n,
          'className',
          val && n.id == val.id ? 'is-selected' : ''
        )
      })
    },
  }
}
</script>
<style lang='scss'>
@import '../../styles/variables.scss';
.inspect-all {
  margin: 66px 18px  0 18px ;
  &-top {
    color: #333333;
    font-size: 17px;
  }
}
.fieldwithmagrin {
  margin: 0px 10px;
  width: 96%;
  height: 55px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.otherleftfieldcss {
  margin-left: -10px;
}
.pointedit .van-hairline--top-bottom::after, .van-hairline-unset--top-bottom::after {
  left: -44%;
  right: -44%;
  border-color: #D2D2D2;
} 
.is-selected {
  background: #f3f9ff;
  color: $color-theme;
}
.uploadPictitle_big {
  margin: 20px 0 20px 18px;
  display: flex;
  .uploadPictitle_left {
    color: #333333;
    font-size: 15px;
  }
  .uploadPictitle_right {
    color: #999999;
    font-size: 13px;
  }
  .uploadwithcss {
    position: relative;
    .van-uploader {
      position: absolute;
      bottom: 20px;
      right: 14px;
      font-size: 14px;
      color: #fff;
      padding: 6px 16px;
      border-radius: 16px;
      background: #2979d1;
    }
  }
}

</style>